/*
 * 作者:熊猫
 * 日期:2017 - 3 - 15 10 - 42 - 20
 *
 */

package net.lainiao.morethread.Chapter7.demo1;

import java.util.Date;
import java.util.List;
import java.util.concurrent.*;

/**
 * Created by Administrator on 2017/3/15.
 */
public class MyExecutor extends ThreadPoolExecutor {
    private ConcurrentHashMap<String,Date> startTimes;
    public MyExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
        startTimes=new ConcurrentHashMap<>();
    }

    @Override
    public void shutdown() {
        System.out.println("MyExecutor : Going to shutdown!");
        System.out.println("MyExecutor:Executed Tasks:"+getCompletedTaskCount());
        System.out.println("MyExecutor Running Tasks:"+getActiveCount());
        System.out.println("MyExecutor Pending Tasks:" +getQueue().size());
        super.shutdown();
    }

    @Override
    public List<Runnable> shutdownNow() {
        System.out.println("MyExecutor : Going to shutdownNow");
        System.out.println("MyExecutor:Executed Tasks:"+getCompletedTaskCount());
        System.out.println("MyExecutor Running Tasks:"+getActiveCount());
        System.out.println("MyExecutor Pending Tasks:" +getQueue().size());
        return super.shutdownNow();
    }

    @Override
    protected void beforeExecute(Thread t, Runnable r) {
        System.out.println("MyExecutor : A Task Is Beginning "+t.getName()+":HashCode="+r.hashCode());
        startTimes.put(String.valueOf(r.hashCode()),new Date());
    }

    @Override
    protected void afterExecute(Runnable r, Throwable t) {
        try {
            Future<?> result=(Future<?>) r;
            System.out.println("======================================");
            System.out.println("MyExecutor A Task is Finishing");
            System.out.println("MyExecutor Result:" +result.get() );
            Date startDate=startTimes.remove(String.valueOf(r.hashCode()));
            Date finishDate=new Date();
            long diff=finishDate.getTime()-startDate.getTime();
            System.out.println("MyExecutor : Druation "+diff);
            System.out.println("======================================");
            super.afterExecute(r, t);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }


}
